package com.example.sunmiv1.fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;


import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.NewAddGoodsSkuAdapter;
import com.example.sunmiv1.entity.SkuGoodsInfo;
import com.example.sunmiv1.entity.SkuInfo;
import com.example.sunmiv1.entity.SkuInfoNew;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.ParcelHelper;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.TextCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class ChooseTagDialogFragment extends DialogFragment {

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.cencel)
    Button cencel;
    @BindView(R.id.ok)
    Button ok;
    @BindView(R.id.addGoods_addSku)
    Button addGoodsAddSku;

    Unbinder unbinder;

    private Window window;
    private NewAddGoodsSkuAdapter adapter;
    private FragmentHook mFragmentHook;

    private List<SkuInfoNew> skuInfoList;//
    private List<SkuGoodsInfo> skuGoodsList;// (需要傳到activity中的規格信息)

    private ACache aCache;
    private SkuInfoNew skuInfo;

    @SuppressLint("HandlerLeak")
    private Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 3:
//                    adapter.notifyItemRangeChanged(0,skuInfoList.size());
//                    skuInfoList.add(skuInfo);
//                    adapter.notifyDataSetChanged();
                    //爲獲取skuinfo，添加按鈕不可用
                    break;
                case 4:
                    break;
            }
        }
    };

    private int type;

    public ChooseTagDialogFragment(int type, List<SkuInfoNew> skuInfoList) {
        this.type = type;
        this.skuInfoList=skuInfoList;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.fragment_dialog_choose_tag, null);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initData();
        initListener();
//        setAdapter();
        builder.setView(view);
        return builder.create();
    }

    private void initView() {
        rv.setLayoutManager(new LinearLayoutManager(getActivity()));
    }

    private void initData() {
        aCache = ACache.get(getActivity());
        getSkuList();
        setAdapter();
    }

    private void initListener() {
        adapter.Click(new NewAddGoodsSkuAdapter.Operation() {
            @Override
            public void delete(int position) {
                skuInfoList.remove(position);
                adapter.notifyDataSetChanged();
                if (skuInfoList.size() == 4) {
                    addGoodsAddSku.setVisibility(View.GONE);
                } else {
                    addGoodsAddSku.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void addClass(int position, String className) {
                LogUtil.i("點擊了  addClass");
                addSkuClass(position, className);
            }

            @Override
            public void addSku(int classIndex, String classId, String skuName) {
                LogUtil.i("點擊了  addSkuaddSku");
                addSkuName(classIndex, classId, skuName);
            }

            @Override
            public void setChoose(int index, int skuIndex) {
//                skuInfoList.get(index).getData().get(skuInfoList.get(index).getSelectFlag()).getList().get(skuIndex).setChecked(
//                        !skuInfoList.get(index).getData().get(skuInfoList.get(index).getSelectFlag()).getList().get(skuIndex).isChecked()
//                );
            }

            @Override
            public void refreshHeight() {
            }
        });
    }

    private void setAdapter() {
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        } else {
            adapter = new NewAddGoodsSkuAdapter(getActivity(), skuInfoList);
            rv.setAdapter(adapter);
        }
    }

    @Override
    public void onStart() {

        super.onStart();
        // 下面這些設置必須在此方法(onStart())中才有效

        window = getDialog().getWindow();
        // 如果不設置這句代碼, 那麼彈框就會與四邊都有一定的距離
        window.setBackgroundDrawableResource(android.R.color.transparent);
        // 設置動畫
        window.setWindowAnimations(R.style.DialogFromBottom);

        WindowManager.LayoutParams params = window.getAttributes();
        params.gravity = Gravity.BOTTOM;
        // 如果不設置寬度,那麼即使你在佈局中設置寬度爲 match_parent 也不會起作用
        params.width = getResources().getDisplayMetrics().widthPixels;
        window.setAttributes(params);
    }

    /*添加規格分類名稱*/
    private void addSkuClass(int index, String name) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            if ("1".equals(aCache.getAsString("userType")) || "2".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("name", name);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(getActivity(), Common.ADD_SKU_ATTR, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                try {
                    JSONObject json = new JSONObject(text);
                    if (json.getInt("status") == 1) {
//                        mhandler.sendEmptyMessage(7);
                        for (SkuInfoNew skuInfoNew : skuInfoList) {
                            skuInfoNew.getData().add(new SkuInfoNew.DataBean(json.getString("id"), name, false, new ArrayList<>()));
                        }
//                        skuInfoList.get(index).getData().
                        adapter.notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
            }
        });
    }


    /*添加規格名稱*/
    private void addSkuName(int classIndex, String classId, String skuName) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            if ("1".equals(aCache.getAsString("userType")) || "2".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("attr_id", classId);
            jsonObject.put("name", skuName);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(getActivity(), Common.ADD_SKU_LIST, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                try {
                    JSONObject json = new JSONObject(text);
                    if (json.getInt("status") == 1) {
                        for (SkuInfoNew skuInfoNew : skuInfoList)
                            skuInfoNew.getData().get(classIndex).getList().add(new SkuInfoNew.DataBean.ListBean(json.getString("id"), skuName, true));
                        adapter.notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {

            }
        });

    }


    /*獲取商品規格*/
    private void getSkuList() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            HttpUtils.post(getActivity(), Common.SKU_INFO, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    skuInfo = GsonUtils.JsonToBean(text, SkuInfoNew.class);
                    Message msg = new Message();
                    if (skuInfo.getStatus() == 1) {
                        msg.what = 3;
                    } else {
                        msg.what = 4;
                    }
//                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @OnClick({R.id.addGoods_addSku, R.id.cencel, R.id.ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.addGoods_addSku:
                    if (skuInfo != null) {
                        skuInfoList.add(ParcelHelper.copy(skuInfo));
                    } else {
                        Toast.makeText(getActivity(), "獲取規格列表失敗~", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    for (SkuInfoNew skuInfoNew : skuInfoList) {
                        LogUtil.i("每個list中spinner被選中的值：" + skuInfoNew.getSelectFlag());
                    }
                    if (skuInfoList.size() == 4) {
                        addGoodsAddSku.setVisibility(View.GONE);
                    } else {
                        addGoodsAddSku.setVisibility(View.VISIBLE);
                    }
//                    adapter.notifyDataSetChanged();
                    adapter.notifyItemInserted(skuInfoList.size());
                break;
            case R.id.cencel:
                dismiss();
                break;
            case R.id.ok:
                skuGoodsList = new ArrayList<>();
                EditText addGoodsCode;
                EditText addGoodsFreightNumber;
                EditText addGoodsPurchasePrice;
                EditText addGoodsPrice;
                EditText addGoodsStock;
                if (type == 1) {
                    addGoodsCode = getActivity().findViewById(R.id.addGoods_barcode_edit);
                    addGoodsFreightNumber = getActivity().findViewById(R.id.addGoods_freightNumber);
                    addGoodsPurchasePrice = getActivity().findViewById(R.id.addGoods_purchasePrice);
                    addGoodsPrice = getActivity().findViewById(R.id.addGoods_price);
                    addGoodsStock = getActivity().findViewById(R.id.addGoods_stock);
                } else {
                    addGoodsCode = getActivity().findViewById(R.id.newAddGood_code);
                    addGoodsFreightNumber = getActivity().findViewById(R.id.newAddGood_freightNumber);
                    addGoodsPurchasePrice = getActivity().findViewById(R.id.newAddGood_purchasePrice);
                    addGoodsPrice = getActivity().findViewById(R.id.newAddGood_retailPrice);
                    addGoodsStock = getActivity().findViewById(R.id.newAddGood_goodsNum);
                }
                freightNumber = addGoodsFreightNumber.getText().toString().trim();
                code = addGoodsCode.getText().toString().trim();
                purchasePrice = addGoodsPurchasePrice.getText().toString().trim();
                price = addGoodsPrice.getText().toString().trim();
                stock = addGoodsStock.getText().toString().trim();

                List<List<SkuInfoNew.DataBean.ListBean>> skuArr = new ArrayList<>();
                int[] flagArr = {-1, -1, -1, -1};
                for (int i = 0; i < skuInfoList.size(); i++) {
                    // 檢查是否有重複選擇skuClass  之後有重複的就忽略
                    for (int i1 = 0; i1 < flagArr.length; i1++) {
                        if (flagArr[i1] == skuInfoList.get(i).getSelectFlag()) {
                            break;
                        } else {
                            flagArr[i] = skuInfoList.get(i).getSelectFlag();
                        }
                    }
                }
                for (int i = 0; i < flagArr.length; i++) {
                    if (flagArr[i] != -1) {
                        skuArr.add(new ArrayList<>());
                        for (SkuInfoNew.DataBean.ListBean bean :
                                skuInfoList.get(i).getData().get(skuInfoList.get(i).getSelectFlag()).getList()) {
                            if (bean.isChecked()) {
                                skuArr.get(i).add(bean);
                            }
                        }
                    }
                }

                // 打印skuArr
                for (int i = 0; i < skuArr.size(); i++) {
                    for (int i1 = 0; i1 < skuArr.get(i).size(); i1++) {
                        LogUtil.i("打印skuArr:[" + i + "][" + i1 + "]" + skuArr.get(i).get(i1).getName());
                    }
                }

                setSkuGoodsInfoList(skuArr);
                if (type == 1) {
                    LinearLayout addGoodsSkuGoodsLin = getActivity().findViewById(R.id.addGoods_skuGoodsLin);
                    View addGoodsSkuGoodsView = getActivity().findViewById(R.id.addGoods_skuGoodsView);
                    if (skuGoodsList.size() > 0) {
                        addGoodsSkuGoodsLin.setVisibility(View.VISIBLE);
                        addGoodsSkuGoodsView.setVisibility(View.VISIBLE);
                    } else {
                        addGoodsSkuGoodsLin.setVisibility(View.GONE);
                        addGoodsSkuGoodsView.setVisibility(View.GONE);
                    }
                } else {
                    LinearLayout addGoodsSkuGoodsLin = getActivity().findViewById(R.id.newAddGood_skuGoodsLin);
                    if (skuGoodsList.size() > 0) {
                        addGoodsSkuGoodsLin.setVisibility(View.VISIBLE);
                    } else {
                        addGoodsSkuGoodsLin.setVisibility(View.GONE);
                    }
                }
                mFragmentHook.backSkuGoodsList(skuGoodsList,skuInfoList);
                dismiss();
                break;
        }
    }


    private String freightNumber;           //  貨號
    private String code;                    //  條碼
    private String purchasePrice;           //  採購價
    private String price;                   //  售價
    private String stock;                   //  庫存

    /**
     * 向skuGoodsList存入數據
     *
     * @param list 二維數組  最多[3][?]
     */
    private void setSkuGoodsInfoList(List<List<SkuInfoNew.DataBean.ListBean>> list) {
        List<List<String>> tempIdSet, idSet = new ArrayList<>();
        List<List<String>> tempNameSet, nameSet = new ArrayList<>();
        List<String> tempIdList, tempNameList;

        List<String> idList, nameList;

        // 非遞歸求n數組相乘
        if (!list.isEmpty()) {
            for (int i = 0; i < list.get(0).size(); i++) {
                idList = new ArrayList<>();
                nameList = new ArrayList<>();
                idList.add(list.get(0).get(i).getId());
                idSet.add(idList);
                nameList.add(list.get(0).get(i).getName());
                nameSet.add(nameList);
            }
            int count = 1;
            while (count < list.size()) {
                tempIdSet = new ArrayList<>(idSet);
                idSet.clear();
                tempNameSet = new ArrayList<>(nameSet);
                nameSet.clear();
                for (List<String> arr : tempIdSet) {
                    for (int i = 0; i < list.get(count).size(); i++) {
                        tempIdList = new ArrayList<>(arr);
                        tempIdList.add(list.get(count).get(i).getId());
                        idSet.add(tempIdList);
                    }
                }
                for (List<String> arr : tempNameSet) {
                    for (int i = 0; i < list.get(count).size(); i++) {
                        tempNameList = new ArrayList<>(arr);
                        tempNameList.add(list.get(count).get(i).getName());
                        nameSet.add(tempNameList);
                    }
                }
                ++count;
            }
        }

        for (int i = 0; i < idSet.size(); i++) {
            addSkuGoodsInfo(idSet.get(i), nameSet.get(i), i);
        }

    }

    /* 添加SkuGoodsInfo*/
    private void addSkuGoodsInfo(List<String> idList, List<String> nameList, int index) {
        String s = "";
        String c = "";
        if (!TextUtils.isEmpty(freightNumber))
            s = freightNumber + "-" + index;
        if (!TextUtils.isEmpty(code))
            c = code + "-" + index;
//        skuGoodsList.add(new SkuGoodsInfo(idList, nameList, s, c, purchasePrice, price, stock));
        skuGoodsList.add(new SkuGoodsInfo(idList, nameList, s, c, purchasePrice, price, ""));
    }

    public interface FragmentHook {
        void backSkuGoodsList(List<SkuGoodsInfo> skuGoodsList,List<SkuInfoNew> skuInfoNews);
    }

    public void setFragmentHook(FragmentHook fragmentHook) {
        mFragmentHook = fragmentHook;
    }

}
